<?php

namespace App\Admin\Forms;


use App\Models\GrExpress;
use App\Models\GrOrder;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;

class UpdateLogistics extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能
    public function __construct($data = [], $key = null)
    {
        $data = GrExpress::all()->toArray();
        $info = [];
        foreach ($data as $val) {
            $info[$val['express_id']] = $val['express_name'];
        }
        $this->info=$info;
        parent::__construct($data, $key);
    }

    // 处理请求
    public function handle(array $input)
    {
        // 获取外部传递参数
        $id = $this->payload['id'] ?? null;

        // 表单参数
        $express_id = $input['express_id'] ?? null;
        $express_no = $input['express_no'] ?? null;
        if (! $id) {
            return $this->response()->error('参数错误');
        }

        $user = GrOrder::query()->find($id);

        if (! $user) {
            return $this->response()->error('订单不存在');
        }

        $user->update(['express_id' =>$express_id,'express_no'=>$express_no,'express_company'=>$this->info[$express_id],'delivery_status'=>2,'order_status'=>1]);

        return $this->response()->success('发货成功')->refresh();
    }

    public function form()
    {
        // 获取外部传递参数
        //$id = $this->payload['id'] ?? null;

        $this->select('express_id')->options($this->info)->required();
        // 密码确认表单
        $this->text('express_no')->required();
    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        return [
            'express_id'         => '',
            'express_no' => '',
        ];
    }
}
